/**
 * 
 */
package com.test.activityMq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者
 * @author liya
 * 上午10:43:21
 */
public class ActivityProducter {
	
	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;
	private static final int SENDNUM = 10;	//发送的消息数
	
	public static void main(String args[]){
		ConnectionFactory connectionFactory; //连接工厂
		Connection connection = null; //连接
		Session session; //会话 接受或者发送消息的线程
		Destination destination; //消息目的地
		MessageProducer messageProducer; //消息生产者
		
		//实例化连接工厂
		connectionFactory = new ActiveMQConnectionFactory(ActivityProducter.USERNAME, ActivityProducter.PASSWORD, ActivityProducter.BROKERURL);
		
		try {
			connection = connectionFactory.createConnection();	//通过连接工厂获取连接
			connection.start(); //启动连接
			session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
			destination = session.createQueue("FirstQueue1");//创建消息队列
			messageProducer = session.createProducer(destination); //创建消息生产者
			sendMessage(session, messageProducer); //调用发送方法
			session.commit(); //提交事物
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 发送消息
	 * @param session
	 * @param messageProducer
	 * @throws Exception
	 */
	public static void sendMessage(Session session, MessageProducer messageProducer) throws Exception{
		for (int i = 0; i < ActivityProducter.SENDNUM; i++) {
			TextMessage message = session.createTextMessage("ActiveMQ 发送消息"+i);
			System.out.println("ActiveMQ发送的"+i+"条消息");
			messageProducer.send(message);
		}
	}
}
